import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:httpx/library.dart';
import 'package:smartloan_mdc/extension/extension.dart';
import 'package:smartloan_mdc/res/string.dart';
import 'package:smartloan_mdc/utils/common/utils.dart';
import 'package:smartloan_mdc/utils/locator/api_address.dart';
import 'package:smartloan_mdc/utils/locator/locator.dart';
import 'package:sml_encrypt/encrypt/encrypt.dart';
import 'package:trace/trace.dart';

import '../../utils/storage/get_storage.dart';

class BaseInterceptor extends Interceptor {
  
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {

    if (!(await Utils.checkNetWork())) {
      handler.reject(DioError(requestOptions: options, error: AppStr.networkError));
    }

    Map<String, dynamic> addHeaders = {};
    String token = AppStorage().readKey(StorageKey.token) ?? '';
    if (token.isNotEmpty) {
      addHeaders.addAll({"Authorization": "Bearer $token"});
    }
    addHeaders.addAll({"traceId": Trace().traceId});

    if (options.path.contains('/zip6in1')) {
      options.headers['contentType'] = "multipart/form-data";
      options.headers['content-type'] = "multipart/form-data";
    }

    if (options.path.contains('/login')) {
      options.headers['contentType'] = "application/x-www-form-urlencoded";
      options.headers['content-type'] = "application/x-www-form-urlencoded";
    }

    if (locator<ApiAddress>().encrypt) {

      if (!(options.path.contains('/zip8in1'))) {
        // encrypt path
        debugPrint('=== 加密前path: ${options.path} \n');
        String encryptPath = SmlEncryptUtil().encrypt16(options.path);
        options.path = encryptPath;
      }
      
      // encrypt data
      var data = options.data;
      debugPrint('=== 加密前参数: \n');
      if (data is Map) {
        debugPrint('  ${jsonEncode(data)}');
      } else {
        debugPrint('${data}');
      }

      if (data is Map) {
        options.data = SmlEncryptUtil().encrypt16(jsonEncode(data));
      }
    }

    options.headers.addAll(addHeaders);

    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    if (locator<ApiAddress>().encrypt) {
      var data = response.data;
      response.data = jsonDecode(SmlEncryptUtil().decrypt16(data));
      debugPrint('=== 解密返回: \n');
      debugPrint('=== ${response.data}');
    }
    super.onResponse(response, handler);
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    // hideLoading();
    super.onError(err, handler);
  }
}